<template>
  <div id="downloadDom"
    ref="downloadDom"
    style="display: none;">
    <div class="download-data"
      :class="{'pdf': downloadType==='pdf'}">
      <div class="download-page px-8 pb-10 relative"
        v-for="(pageItem, pageKey) in tableDta"
        :key="pageKey">
        <div class="header flex items-center justify-between py-10 border-b border-purple-1300">
          <div class="logo">
            <img style="height: 46px;"
              src="@/static/images/logo.png" />
          </div>
          <div class="text-right">
            <h3 class="text-lg text-gray-1000 font-semibold">{{$t('download_header_title')}}</h3>
            <p class="text-sm text-gray-1500">{{$t('download_header_desc',{toolNum:  $options.filters['formatTotal'](toolCount)})}}</p>
          </div>
        </div>
        <div class="flex items-center justify-between py-8">
          <div class="flex items-center">
            <img class="w-6 mr-3"
              src="@/assets/images/category_selected.png" />
            <span class="text-xl text-gray-1000 font-semibold">
              {{title}}
            </span>
          </div>
          <slot name="data"></slot>
        </div>
        <!-- category -->
        <download-table-new01 v-if="tableType===1"
          :pageDataNum="pageDataNum"
          :pageKey="pageKey"
          :tableData="pageItem"></download-table-new01>
        <!-- regions -->
        <download-table-new02 v-if="tableType===2"
          :pageDataNum="pageDataNum"
          :region="region"
          :pageKey="pageKey"
          :tableData="pageItem"></download-table-new02>
        <!-- source -->
        <download-table-new03 v-if="tableType===3"
          :pageDataNum="pageDataNum"
          :handle="handle"
          :pageKey="pageKey"
          :tableData="pageItem"></download-table-new03>
        <!-- Month -->
        <download-table-new04 v-if="tableType===4"
          :pageDataNum="pageDataNum"
          :pageKey="pageKey"
          :tableData="pageItem"></download-table-new04>
        <!-- Revenue -->
        <download-table-new05 v-if="tableType===5"
          :pageDataNum="pageDataNum"
          :pageKey="pageKey"
          :tableData="pageItem"></download-table-new05>
        <!-- <download-table01 v-if="tableType===1"
          :pageDataNum="pageDataNum"
          :pageKey="pageKey"
          :tableData="pageItem"></download-table01>
        <download-table02 v-if="tableType===2"
          :isCatagory="$route.params.category ? true : false"
          :isRegion="$route.name === 'lang-Best-AI-Tools-region-region' || $route.name==='Best-AI-Tools-region-region'"
          :handle="handle"
          :isSource="$route.name === 'lang-Best-AI-Tools-Source-source' || $route.name==='Best-AI-Tools-Source-source'"
          :pageDataNum="pageDataNum"
          :pageKey="pageKey"
          :tableData="pageItem"></download-table02>
        <download-table03 v-if="tableType===3"
          :pageDataNum="pageDataNum"
          :pageKey="pageKey"
          :tableData="pageItem"></download-table03> -->
        <p class="text-sm mt-6 text-gray-1400 break-words"
          v-if="pageKey===tableDta.length-1">
          <span class="mr-5">{{ $t('download_footer_desc') }}</span>
          <span>{{ $t('download_footer_desc2') }}</span>
        </p>
        <div class="flex justify-center"
          v-if="pageKey===tableDta.length-1 && downloadType==='pdf'">
          <div class="download_btn inline-flex items-center justify-center h-12 text-base font-semibold text-white bg-purple-1300 px-6 rounded whitespace-nowrap hover:opacity-90">
            {{ $t('download_btn') }}
          </div>
        </div>
        <iframe id="output"
          v-if="downloadType==='pdf'"></iframe>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  name: 'DownloadDom',
  props: {
    list: {
      type: Array,
      default() {
        return []
      },
    },
    region: {
      type: Object,
      default() {
        return {}
      },
    },

    title: {
      type: String,
      default: '',
    },
    handle: {
      type: String | null,
      default: null,
    },

    downloadType: {
      type: String,
      default: 'pdf',
    },
    pageDataNum: {
      type: Number,
      default: 10,
    },
    toolCount: {
      type: Number,
      default: 0,
    },
    tableType: {
      type: Number,
      default: 2,
    },
  },
  computed: {
    ...mapState({
      locale: (state) => state.locale,
    }),
    tableDta() {
      let result = []
      if (this.downloadType === 'pdf') {
        for (let i = 0; i < this.list.length; i += this.pageDataNum) {
          result.push(this.list.slice(i, i + this.pageDataNum))
        }
      } else {
        result.push(JSON.parse(JSON.stringify(this.list)))
      }
      return result
    },
  },
  filters: {
    formatTotal: function (val) {
      if (typeof val === 'number' && !isNaN(val)) {
        if (val < 100) {
          return val
        }
        let numStr = String(parseInt(val))
        const len = numStr.length
        const arr = numStr.split('')
        for (let i = 0; i < len; i++) {
          arr[i] = i < len - 2 ? arr[i] : '0'
        }
        return `${arr.join('')}+`
      } else {
        return val
      }
    },
  },
  methods: {
    getPdf() {
      const spCloned = document.getElementById('downloadDom') //传入的id名称
      spCloned.style.zIndex = -100
      spCloned.style.position = 'fixed'
      spCloned.style.top = '-999999px'
      spCloned.style.width = '1000px'
      spCloned.style.display = 'block'
      let that = this
      this.$html2canvas(spCloned, {
        allowTaint: true,
        dpi: 120,
      }).then(function (canvas) {
        const contentWidth = canvas.width
        const contentHeight = canvas.height
        const pageHeight = (contentWidth / 592.28) * 841.89
        let leftHeight = contentHeight
        let position = 0
        const imgWidth = 595.28
        const imgHeight = (592.28 / contentWidth) * contentHeight
        //console.log(imgHeight, contentHeight)
        const pageData = canvas.toDataURL('image/jpeg', 1.0)
        const PDF = new that.$JsPDF('', 'pt', 'a4')

        let page = 0
        var drawHyLink = function (isLast) {
          PDF.link(16, 20, 130, 33, {
            url: 'https://www.toolify.ai/',
          })

          if (isLast) {
            let uri = window.location.href
            PDF.link(215, 805, 155, 32, {
              url: uri,
            })
          }
          that.tableDta[page].forEach((item, key) => {
            if (
              that.tableType === 1 ||
              that.tableType === 4 ||
              that.tableType === 5
            ) {
              PDF.link(76, 161 + 61 * key, 100, 61, {
                url: `${window.location.origin}/tool/${item.handle}`,
              })
            } else if (that.tableType === 2 || that.tableType === 3) {
              PDF.link(69, 161 + 61 * key, 89, 61, {
                url: `${window.location.origin}/tool/${item.handle}`,
              })
            }
          })
        }

        if (leftHeight < pageHeight) {
          PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
          drawHyLink()
        } else {
          while (leftHeight > 0) {
            PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
            leftHeight -= pageHeight
            position -= 841.89
            if (leftHeight > 0) {
              drawHyLink()
              PDF.addPage()
            } else {
              drawHyLink(true)
            }
            page += 1
          }
        }

        that.$emit('downloadStatus', null)
        PDF.save(that.title + '.pdf')
      })
    },
    getPic() {
      let that = this
      window.pageYoffset = 0
      document.documentElement.scrollTop = 0
      document.body.scrollTop = 0
      // 先获取你要转换为img的dom节点
      let node = document.getElementById('downloadDom') //传入的id名称

      node.style.zIndex = -100
      node.style.position = 'fixed'
      node.style.top = '-999999px'
      node.style.display = 'block'

      let width = 1000 //dom宽
      let height = node.offsetHeight //dom高
      node.style.width = width
      node.style.height = height
      let scale = 2 //放大倍数 这个相当于清晰度 调大一点更清晰一点

      this.$html2canvas(node, {
        width: width,
        heigth: height,
        backgroundColor: '#ffffff', //背景颜色 为null是透明
        dpi: window.devicePixelRatio * 2, //按屏幕像素比增加像素
        scale: scale,
        X: 0,
        Y: 0,
        scrollX: -3, //如果左边多个白边 设置该偏移-3 或者更多
        scrollY: -50,
        useCORS: true, //是否使用CORS从服务器加载图像 !!!
        allowTaint: true, //是否允许跨域图像污染画布  !!!
      }).then((canvas) => {
        // console.log("canvas", canvas);
        var url = canvas.toDataURL() //这里上面不设值cors会报错
        var a = document.createElement('a') //创建一个a标签 用来下载
        a.download = that.title //设置下载的图片名称
        var event = new MouseEvent('click') //增加一个点击事件
        that.dataURL = url
        //如果需要下载的话就加上这两句
        a.href = url //此处的url为base64格式的图片资源
        a.dispatchEvent(event) //触发a的单击事件 即可完成下载

        that.$emit('downloadStatus', null)
      })
    },
  },
}
</script>
<style lang="scss" scoped>
.download-data {
  width: 1000px;
  /* display: none;
  position: fixed;
  top: -999999px; */
  background: #fff;
  font-family: Helvetica, 'Helvetica Neue', 'PingFang SC', 'Hiragino Sans GB',
    'Microsoft YaHei', '微软雅黑', Arial, sans-serif !important;

  &.pdf {
    width: 1000px !important;

    .download-page {
      height: 1421px;
    }
  }
  .dTable {
    background: #ffffff;
    border-radius: 6px;
    border: 1px solid #e5e5e5;
    overflow: hidden;
    table {
      td,
      th {
        box-sizing: border-box;
        min-width: 0;
        padding: 12px 0;
        position: relative;
        text-align: left;
        text-overflow: ellipsis;
        vertical-align: middle;
        .cell {
          box-sizing: border-box;
          display: inline-block;
          padding-left: 10px;
          padding-right: 10px;
          position: relative;
          vertical-align: middle;
          width: 100%;
          text-overflow: ellipsis;
          overflow: hidden;
          text-align: center;
        }
        &:first-child {
          .cell {
            padding-left: 22px;
            text-align: center;
          }
        }
        &:last-child {
          .cell {
            padding-right: 22px;
            text-align: center;
          }
        }
      }
      thead {
        tr {
          th {
            background: #7150e6;
            color: #fff;
            font-weight: 400;
            border-bottom: 1px solid #e5e5e5;
            & + th {
              border-left: 1px solid #e5e5e5;
            }
          }
        }
      }
      tbody {
        tr {
          td {
            border-bottom: 1px solid #e5e5e5;
            color: #191919;
            font-size: 16px;
            padding-bottom: 10px;
            padding-top: 10px;
            .no-color {
              color: rgba(0, 0, 0, 0);
            }
            & + td {
              border-left: 1px solid #e5e5e5;
            }
          }
          &:nth-child(even) {
            background: #f8f9fb;
          }
          &:last-child {
            td {
              border-bottom: 0;
            }
          }
        }
      }
    }
  }

  .download_btn {
    position: absolute;
    left: 50%;
    top: 1350px;
    width: 250px;
    transform: translateX(-50%);
  }
}
</style>
